import bcrypt
from app.utils.exceptions import InternalServerError


# 注册时哈希密码
def hash_password(password):
    # 生成盐并哈希密码（自动处理盐）
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hashed.decode('utf-8')  # 存储为字符串


# 登录时验证密码
def verify_password(stored_hash, input_password):
    try:
        return bcrypt.checkpw(input_password.encode('utf-8'), stored_hash.encode('utf-8'))
    except Exception as e:
        raise InternalServerError() from e


# 示例使用
# hashed = hash_password("mypassword")
# print(hashed)  # 类似：$2b$12$Sx4fU...（包含算法、盐、哈希）
#
# result = verify_password(hashed, "mypassword")  # True
# print(result)
